<template>
	<view>
		<map :scale="scale" style="width: 100vw; height: 100vh;" enable-3D="false" show-compass="false"
			enable-overlooking="false" :enable-satellite="false" :enable-traffic="false" show-location="false"
			:latitude="latitude" :longitude="longitude" :markers="covers" :polyline="polyline">
		</map>

	</view>
</template>

<script>
	import QQMapWX from '../../utils/qqmap-wx-jssdk.js';
	var qqmapsdk;
	export default {
		data() {
			return {
				lat: '0',
				lng: '0',
				scale: 16,
				markers: [], // 地标
				latitude: '0',
				longitude: '0',
				polyline: [] // 路线
			};
		},
		onLoad: function(option) { //option为object类型，会序列化上个页面传递的参数
			console.log(option.lat); //打印出上个页面传递的参数。
			console.log(option.lng); //打印出上个页面传递的参数。
			this.lat = option.lat;
			this.lng = option.lng;
			this.latitude = option.latitude;
			this.longitude = option.longitude;
		},
		mounted() {
			this.routePlanning();
		},
		methods: {
			routePlanning() {
				let _that = this;
				qqmapsdk = new QQMapWX({
					key: '55ZBZ-B6EKT-YE2XN-LF5DO-F7RMQ-AVBHN'
				})
				qqmapsdk.direction({
					mode: "transit",
					from: { // 起始位置(当前位置)坐标
						latitude: this.latitude,
						longitude: this.longitude
					},
					to: {
						latitude: this.lat,
						longitude: this.lng
					}, // 目的地位置坐标
					success: function(res) {
						console.log(res);
						var ret = res.result.routes[0];
						var count = ret.steps.length;
						var pl = [];
						var coors = [];
						//获取各个步骤的polyline
						for (var i = 0; i < count; i++) {
							if (ret.steps[i].mode == 'WALKING' && ret.steps[i].polyline) {
								coors.push(ret.steps[i].polyline);
							}
							if (ret.steps[i].mode == 'TRANSIT' && ret.steps[i].lines[0].polyline) {
								coors.push(ret.steps[i].lines[0].polyline);
							}
						}
						//坐标解压（返回的点串坐标，通过前向差分进行压缩）
						var kr = 1000000;
						for (var i = 0; i < coors.length; i++) {
							for (var j = 2; j < coors[i].length; j++) {
								coors[i][j] = Number(coors[i][j - 2]) + Number(coors[i][j]) / kr;
							}
						}
						//定义新数组，将coors中的数组合并为一个数组
						var coorsArr = [];
						for (var i = 0; i < coors.length; i++) {
							coorsArr = coorsArr.concat(coors[i]);
						}
						for (var i = 0; i < coorsArr.length; i += 2) {
							pl.push({
								latitude: coorsArr[i],
								longitude: coorsArr[i + 1]
							})
						}
						//设置polyline属性
						_that.polyline.push({
							points: pl,
							color: '#FF0000DD',
							width: 4
						})
					},
					fail: function(error) {
						console.error(error);
					},
					complete: function(res) {
						console.log(res);
					}
				})
			}
		}
	}
</script>

<style lang="scss">

</style>
